package com.cloudcc.boot.entity.sap;

import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.util.List;

public class OrderConvert {

    public static SapOrderVo convertCrmOrderDtoToSapOrderVo(CrmOrderDto crmOrderDto, SapEnumsProperties sapEnums) {
        SapOrderVo sapOrderVo = new SapOrderVo();
        SapOrderVo.HeaderVo headerVo = new SapOrderVo.HeaderVo();
        headerVo.setVBELN(crmOrderDto.getRecordName());
        headerVo.setAUART(sapEnums.getOrderTypeCode(crmOrderDto.getOrderType()));
        headerVo.setVKORG(sapEnums.getSalesOrgCode(crmOrderDto.getSalesOrg()));
        headerVo.setVTWEG(sapEnums.getSalesChannelCode(crmOrderDto.getSalesChannel()));
        headerVo.setSPART(sapEnums.getProductGroupCode(crmOrderDto.getProductGroup()));
        headerVo.setKUNAG(crmOrderDto.getSoldAccountSapCode());
        headerVo.setKUNNR(crmOrderDto.getShipAccountSapCode());
        headerVo.setBSTNK(crmOrderDto.getSalesContractNumber());
        headerVo.setBSTDK(crmOrderDto.getSalesContractSignDate());
        headerVo.setZTERM(crmOrderDto.getPaymentTermsCode());
        headerVo.setPRSDT(crmOrderDto.getSalesContractSignDate());
        headerVo.setZZPRZ23(new BigDecimal(crmOrderDto.getPaymentRatio()));
        headerVo.setZZPRZ2301(new BigDecimal(crmOrderDto.getAcceptanceRatio()));
        headerVo.setZZPRZ2302(new BigDecimal(crmOrderDto.getWarrantyRatio()));
        headerVo.setWAERK(StringUtils.substringBefore(crmOrderDto.getCurrency(), "-").trim());
        sapOrderVo.setHEADER(headerVo);
        List<SapOrderVo.ItemVo> itemVos = crmOrderDto.getItems().stream().map(crmItemDto -> {
            SapOrderVo.ItemVo itemVo = new SapOrderVo.ItemVo();
            itemVo.setPOSNR(crmItemDto.getRecordName());
            itemVo.setMATNR(crmItemDto.getMaterialCode());
            itemVo.setKWMENG(crmItemDto.getSalesQuantity());
            itemVo.setVRKME(crmItemDto.getUnit());
            itemVo.setNETPR(crmItemDto.getAmount());
            itemVo.setWBS(crmItemDto.getWbsCode());
            return itemVo;
        }).toList();
        sapOrderVo.setITEMS(itemVos);
        return sapOrderVo;
    }

}
